package com.gitee.chessboard.menu;

import com.gitee.chessboard.db.MybatisService;
import com.intellij.CommonBundle;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.event.ActionEvent;

/**
 * @author 敲代码的旺财
 * @date 2021/12/16 16:13
 */
public class DictionaryManagerMenuForm extends DialogWrapper {

    private JTextField db;
    private JTextField username;
    private JTextField password;
    private JPanel mainPanel;
    private JTextPane errorPane;
    PropertiesComponent propertiesComponent;
    Project project;

    public DictionaryManagerMenuForm(Project project) {
        super(project,true);
        this.propertiesComponent = PropertiesComponent.getInstance(project);
        this.project = project;
        this.db.setText(this.propertiesComponent.getValue(DictionaryManagerMenu.DB_CODE));
        this.username.setText(this.propertiesComponent.getValue(DictionaryManagerMenu.USERNAME_CODE));
        this.password.setText(this.propertiesComponent.getValue(DictionaryManagerMenu.PASSWORD_CODE));
        setTitle("字典管理");
        init();
    }

    @Override
    protected @Nullable JComponent createCenterPanel() {
        return getMainPanel();
    }

    public JPanel getMainPanel() {
        return mainPanel;
    }

    @Override
    protected @NotNull Action getOKAction() {
        return new DialogWrapperAction(CommonBundle.getOkButtonText()) {
            @Override
            protected void doAction(ActionEvent e) {
                propertiesComponent.setValue(DictionaryManagerMenu.DB_CODE,db.getText());
                propertiesComponent.setValue(DictionaryManagerMenu.USERNAME_CODE,username.getText());
                propertiesComponent.setValue(DictionaryManagerMenu.PASSWORD_CODE,password.getText());
                MybatisService mybatisService = ServiceManager.getService(project, MybatisService.class);
                mybatisService.setUrl(db.getText());
                mybatisService.setUsername(username.getText());
                mybatisService.setPassword(password.getText());
                mybatisService.init();
                String error = mybatisService.connectTest();
                if (error == null) {
                    doOKAction();
                }else {
                    errorPane.setText(error);
                }
            }
        };
    }
}
